#include "udp_server.hpp"
#include <iostream>
#include <memory>

using namespace std;

static void usage(string proc)
{
    cout << "Usage:\n\t" << proc << " port\n" << endl;
}

// 转大写
string to_up(string str)
{
    string res;
    for(auto& it : str)
    {
        if(it >= 'a' && it <= 'z')
        {
            it -= 32;
        }
        res.push_back(it);
    }
    return res;
}

static bool check(string& str)
{
    if(str.find("rm") != string::npos) return false;
    if(str.find("mv") != string::npos) return false;
    if(str.find("kill") != string::npos) return false;
    if(str.find("while") != string::npos) return false;
    return true;
}

// client给server发命令，server将结果返回给client
string execute_command(string command)
{
    if(check(command) == false) return "非法命令";

    FILE *fp = popen(command.c_str(), "r");
    if(fp == nullptr)
    {
        return "none";
    }

    char line[1024];
    string res;
    while(fgets(line, sizeof(line), fp) != nullptr)
    {
        res += line;
    }
    pclose(fp);

    return res;
}

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);

    std::cout << "serve" << std::endl;
    // unique_ptr<violet::udp_server> s(new violet::udp_server(port));
    // unique_ptr<violet::udp_server> s(new violet::udp_server(to_up, port));
    unique_ptr<violet::udp_server> s(new violet::udp_server(execute_command, port));

    s->InitServer();
    s->Start();

    return 0;
}